<template>
	<div ref="chartDom" style="width: 100%; height: 100%; padding-top: 70px;"></div>
</template>

<script setup>
import { ref, defineProps, watch, nextTick, onMounted, onUnmounted } from 'vue';
import * as Echarts from 'echarts';

const chartDom = ref(null);
const myChart = ref(null);

const props = defineProps({
	data: {
		type: Number,
		default: 0
	},
	title: {
		type: String,
	}
});

const options = ref({
	title: {
		text: '',
		left: 'center',
		textStyle: {
			fontSize: 36,
			color: '#fff'
		},
	},
	center: ['50%', '70%'],
	series: [
		{
			type: 'gauge',
			axisLine: {
				lineStyle: {
					width: 10,
					color: [
						[0.3, '#67e0e3'],
						[0.7, '#37a2da'],
						[1, '#fd666d']
					]
				}
			},
			pointer: {
				itemStyle: {
					color: 'auto'
				}
			},
			axisTick: {
				distance: -10,
				length: 8,
				lineStyle: {
					color: '#fff',
					width: 2
				}
			},
			splitLine: {
				distance: 0,
				length: 0,
				lineStyle: {
					color: '#fff',
					width: 4
				}
			},
			axisLabel: {
				color: 'inherit',
				distance: 20,
				fontSize: 10
			},

			detail: {
				valueAnimation: true,
				formatter: '{value} %',
				color: 'inherit'
			},
			data: [
				{
					value: 0
				}
			]
		}
	]
});

const resize = () => {
	if (myChart.value) {
		myChart.value.resize();
	}
};

let pendingData = null;

watch(
	() => props.data,
	(newValue) => {
		pendingData = newValue;
		if (myChart.value) {
			updateChart(newValue);
		}
	},
	{ immediate: true }
);

onMounted(() => {
	nextTick(() => {
		try {
			console.log('props.data: ' + props.data)

			myChart.value = Echarts.init(chartDom.value);
			myChart.value.setOption(options.value);
			if (pendingData !== null) {
				updateChart(pendingData);
				pendingData = null;
			}
		} catch (error) {
			console.error('ECharts 初始化失败:', error);
		}
	});
	window.addEventListener('resize', resize);
});

function updateChart(value) {
	options.value.series[0].data[0].value = value;
	options.value.title.text = props.title;
	myChart.value.setOption(options.value);
}

onUnmounted(() => {
	window.removeEventListener('resize', resize);
	if (myChart.value) {
		myChart.value.dispose();
	}
});
</script>

<style scoped lang="scss">
/* 可以在这里添加样式 */
</style>